package day53_416;

/**
 * @ClassName Solution
 * @Description DP解法
 * @Author clockTown
 * @Date 2021/7/1 20:36
 * @Version 1.0
 */
public class Solution2 {
    public boolean canPartition(int[] nums) {
        int n = nums.length;
        if (n < 2) {
            return false;
        }
        int sum = 0, maxNum = 0;
        for (int num : nums) {
            maxNum = Math.max(maxNum, num);
            sum += num;
        }
        if (sum % 2 == 1) {
            return false;
        }

        int target = sum / 2;
        if (maxNum > target) {
            return false;
        }

        boolean[] dp = new boolean[target + 1];
        //如果不取任何数, 则整数和为0
        dp[0] = true;

        for (int i = 0; i < n; i++) {
            for (int j = target; j > 0; j--) {
                dp[j] = dp[j] || (j - nums[i] >= 0 && dp[j - nums[i]]);
            }
        }
        return dp[target];
    }
}
